﻿using CsvHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Lottery.Classes
{
    public class TxtData<T>
    {

        private String fileName;

        public TxtData(string fileName)
        {
            this.fileName = fileName;
        }

        private Type classMap;

        private int skipLine  = 0;

        public int SkipLine { get => skipLine; set => skipLine = value; }
        public Type ClassMap { get => classMap; set => classMap = value; }

        public List<T> readToObject()
        {
            List<T> datas = new List<T>();
            if (!System.IO.File.Exists(fileName))
            {
                return datas;
            }
            using (TextReader txt = new StreamReader(fileName, Encoding.Default))
            {
                Type type = typeof(T);
                for (int j = 0; j < skipLine; j++)
                {
                    Console.WriteLine(txt.ReadLine());
                }
                using (var csv = new CsvReader(txt))
                {
                    csv.Configuration.Delimiter = "\t";
                    if (classMap != null)
                    {
                        csv.Configuration.RegisterClassMap(classMap);
                    }
                     datas = new List<T>(csv.GetRecords<T>());
                    //string json = JsonConvert.SerializeObject(records);


                }

            }
            return datas;
        }
    

      


        public void write(T record)
        {

            List<T> records = new List<T>();
            records.Add(record);
            using (TextWriter writer = new StreamWriter(this.fileName, true, Encoding.Default))
            {
                using (var csv = new CsvWriter(writer))
                {
                    //csv.WriteHeader(typeof(T));
                    csv.Configuration.Delimiter = "\t";
                    csv.Configuration.HasHeaderRecord = false;
                    csv.Configuration.RegisterClassMap(classMap);
                    if (records == null || records.Count <= 0)
                        return;
                    csv.WriteRecords<T>(records);
                }
            }


        }

        public void write(List<T> records )
        {
            using (TextWriter writer = new StreamWriter(this.fileName ,false,Encoding.Default))
            {
                using (var csv = new CsvWriter(writer))
                {
                    //csv.WriteHeader(typeof(T));
                    csv.Configuration.Delimiter = "\t";
                    csv.Configuration.RegisterClassMap(classMap);
                    if (records == null || records.Count <= 0)
                        return;
                    csv.WriteRecords<T>(records);
                }
            }
        }

 

       
    }
}
